<?php
class FilmController extends FrontController {
	/**
	 *
	 * @var string the default layout for the views. Defaults to
	 *      '//layouts/column2', meaning
	 *      using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout = '//layouts/column2';
	
	/**
	 *
	 * @return array action filters
	 */
	public function filters() {
		return array (
				'accessControl'  // perform access control for CRUD operations
		);
	}
	
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * 
	 * @return array access control rules
	 */
	public function accessRules() {
		return array (
				array (
						'allow', // allow all users to perform 'index' and
						               // 'view' actions
						'actions' => array (
								'index',
								'free',
								'hot',
								'new',
								'jview',
								'jlist'
						),
						'users' => array (
								'*' 
						) 
				),
				
				array (
						'allow', // allow authenticated user to perform 'create'
						               // and 'update' actions
						'actions' => array (
								'view' 
						),
						'users' => array (
								'@' 
						) 
				),
				array (
						'deny', // deny all users
						'users' => array (
								'*' 
						) 
				) 
		);
	}
	/**
	 * Displays a particular model.
	 * 
	 * @param integer $id
	 *        	the ID of the model to be displayed
	 */
	public function actionFree($id) {
		$model = $this->loadModel ( $id );
		$criteriaE = new CDbCriteria ();
		$criteriaE->condition = 't.fid = ' . $model->id . ' AND t.active=1';
		$criteriaE->order = 't.order ASC';
		$dataProviderE = new CActiveDataProvider ( 'Server', array (
				'criteria' => $criteriaE,
				'pagination' => array (
						'pageSize' => 5 
				) 
		) );
		$criteriaF = new CDbCriteria ();
		$criteriaF->condition = 't.id != ' . $model->id . ' AND catid=' . $model->catid . ' AND t.active=1';
		//$criteriaF->order = 't.order ASC';
		$criteriaF->order = 'RAND()';
		$dataProviderF = new CActiveDataProvider ( 'Film', array (
				'criteria' => $criteriaF,
				'pagination' => array (
						'pageSize' => 5 
				) 
		) );
		$this->render ( 'free', array (
				'model' => $model,
				'dataProviderE' => $dataProviderE,
				'dataProviderF' => $dataProviderF 
		) );
	}
	public function actionView($id) {
		$member = new Member ();
// 		$member = Member::model ()->findByPk ( Yii::app ()->user->id );
		$trans = Transpackage::model ()->findByAttributes ( array ('mid' => Yii::app ()->user->id,),array('order'=>'t.id DESC') );
		$Session=new Session('User');
		$Session->Set('url',Yii::app()->request->url);
		if ($trans != null) {
			if( strtotime($trans->enddate) >=  strtotime(date('Y-m-d H:i'))){
				$model = $this->loadModel ( $id );
				$criteriaE = new CDbCriteria ();
				$criteriaE->condition = 't.fid = ' . $model->id . ' AND t.active=1';
				$criteriaE->order = 't.order ASC';
				$dataProviderE = new CActiveDataProvider ( 'Server', array (
						'criteria' => $criteriaE,
						'pagination' => array (
								'pageSize' => 5 
						) 
				) );
				$criteriaF = new CDbCriteria ();
				$criteriaF->condition = 't.id != ' . $model->id . ' AND catid=' . $model->catid . ' AND t.active=1';
				//$criteriaF->order = 't.order DESC';RAND()
				$criteriaF->order = 'RAND()';
				$dataProviderF = new CActiveDataProvider ( 'Film', array (
						'criteria' => $criteriaF,
						'pagination' => array (
								'pageSize' => 5 
						) 
				) );
				$this->render ( 'view', array (
						'model' => $model,
						'dataProviderE' => $dataProviderE,
						'dataProviderF' => $dataProviderF 
				) );
			}
			else{
				Yii::app ()->user->setFlash ( 'warning', "Bạn đã hết thời gian sử dụng dịch vụ. Để xem nội dung đầy đủ bạn phải đăng ký gói dịch vụ:" );
				$this->redirect ( array ('/package' ) );
			}
		} else {
			Yii::app ()->user->setFlash ( 'warning', "Để xem nội dung đầy đủ bạn phải đăng ký gói dịch vụ:" );
			$this->redirect ( array ('/package' ) );
// 			Yii::app ()->user->setFlash ( 'warning', "Bạn đã hết thời gian sử dụng dịch vụ" );
// 			$this->redirect ( array ('/member/about' ) );
		}
	}
	public function actionJview($id){
		if(isset($_POST['user']) && isset($_POST['passwd'])){
			if(($_POST['user'] === 'mbapp') && ($_POST['passwd'] === '6EVAje6U')){
				$model = $this->loadModel($id);
				$server=Server::model()->findAllByAttributes(array('fid'=>$model->id,'active'=>'1'),array('order'=>'t.order asc'));
				$arr=array();
				foreach($server as $s){
					$espisode=array($s->name=>array(
							'episode'=>Episode::model()->findAllByAttributes(array('eid' => $s->id)),
							'pathfile'=>array($s->en_name)
							));
					$arr=CMap::mergeArray($arr,$espisode);
				}
				header('Content-type: application/json');
				
				$jsondata = array('filmdetail' =>array($model),
							'server'=>$arr,
						);
				echo CJSON::encode($jsondata);
				Yii::app()->end();
			}
		}
	}
	public function actionJlist()
	{
		if(isset($_POST['user']) && isset($_POST['passwd'])){
			if(($_POST['user'] === 'mbapp') && ($_POST['passwd'] === '6EVAje6U')){
				// New
				$criteriaNew = new CDbCriteria ();
				$criteriaNew->condition = "t.active=1";
				$criteriaNew->order = 't.id DESC';
				$FdataProvider = new CActiveDataProvider ( 'Film', array (
						'criteria' => $criteriaNew,
						'pagination' => array (
								'pageSize' => 10
						)
				) );
				header('Content-type: application/json');
	
				$jsondata = array('filmlist' =>$FdataProvider->getData(),
						'pageinfo'=>array(
								array(
										'pagecount'=>$FdataProvider->getPagination()->getPageCount(),
										'currentpage'=>$FdataProvider->getPagination()->currentPage,
								)
						));
				echo CJSON::encode($jsondata);
				Yii::app()->end();
			}
		}
	}
	/**
	 * Displays a particular model.
	 * 
	 * @param integer $id
	 *        	the ID of the model to be displayed
	 *        	
	 *        	public function actionView($id)
	 *        	{
	 *        	$member=new Member;
	 *        	$show=Tools::is3G();
	 *        	$key=Yii::app()->request->getParam('key',0);
	 *        	if($key!=0){
	 *        	$temp=Temp::model()->findByPk($key);
	 *        	if($temp!=null){
	 *        	$mem=Member::model()->findByAttributes(array('username'=>$temp->val));
	 *        	$temp->delete();
	 *        	$login=new FrontLoginForm;
	 *        	$login->username=$mem->username;
	 *        	$login->password=$mem->password;
	 *        	$login->rememberMe=true;
	 *        	$login->login();
	 *        	//Yii::app()->user->setFlash('success', "<b>Tài khoản:</b>
	 *        	".$model->username."<br/> <b>Mật khẩu:</b>
	 *        	".$model->password.".<br/> Hãy thay đổi mật khẩu sau lần đăng
	 *        	nhập đầu tiền. Cảm ơn bạn đã sử dụng dịch vụ của MobileTV.");
	 *        	}
	 *        	
	 *        	}
	 *        	if(Yii::app()->user->id!==null){
	 *        	$member=Member::model()->findByPk(Yii::app()->user->id);
	 *        	$model=$this->loadModel($id);
	 *        	$trans=Transaction::model()->findByAttributes(array('mid'=>$member->id,'fid'=>$model->id));
	 *        	if($trans==null){
	 *        	if($member->amount >= $model->retail[0]['price']){
	 *        	// Save transaction
	 *        	$trans=new Transaction();
	 *        	$trans->mid=$member->id;
	 *        	$trans->fid=$model->id;
	 *        	$trans->price=$model->retail[0]['price'];
	 *        	$trans->startdate=date('Y-m-d H:i');
	 *        	$trans->enddate=date('Y-m-d H:i');
	 *        	$trans->active=1;
	 *        	if($trans->save()){
	 *        	$member->amount=$member->amount-$model->retail[0]['price'];
	 *        	if($member->save()){
	 *        	//Get data
	 *        	$criteriaE=new CDbCriteria();
	 *        	$criteriaE->condition = 't.fid = '.$model->id.' AND
	 *        	t.active=1';
	 *        	$criteriaE->order='t.order DESC';
	 *        	$dataProviderE=new CActiveDataProvider('Server', array(
	 *        	'criteria'=>$criteriaE,
	 *        	'pagination'=>array(
	 *        	'pageSize'=>5,
	 *        	),
	 *        	));
	 *        	$criteriaF=new CDbCriteria();
	 *        	$criteriaF->condition = 't.id != '.$model->id.' AND
	 *        	catid='.$model->catid.' AND t.active=1';
	 *        	$criteriaF->order='t.order DESC';
	 *        	$dataProviderF=new CActiveDataProvider('Film', array(
	 *        	'criteria'=>$criteriaF,
	 *        	'pagination'=>array(
	 *        	'pageSize'=>5,
	 *        	),
	 *        	));
	 *        	$this->render('view',array(
	 *        	'model'=>$model,
	 *        	'dataProviderE'=>$dataProviderE,
	 *        	'dataProviderF'=>$dataProviderF,
	 *        	));
	 *        	}
	 *        	}
	 *        	}
	 *        	else{
	 *        	if($show!=''){
	 *        	$Session= new Session('Script');
	 *        	$Session->set('fs',time());
	 *        	$Session->set('id',$model->id);
	 *        	$appid=Yii::app()->params['applicationId'];
	 *        	$appsecret=Yii::app()->params['appSecret'];
	 *        	$p='film_'.$model->id;
	 *        	$s=$Session->Get('fs');
	 *        	$md5=md5($appid.$p.$appsecret.$s);
	 *        	$link=Yii::app()->params['paymentUrl'].'?a='.$appid.'&p='.$p.'&s='.$s.'&md5='.$md5;
	 *        	$this->redirect($link);
	 *        	}
	 *        	else {
	 *        	Yii::app()->user->setFlash('warning', "Tài khoản của bạn hiện
	 *        	không đủ để xem phim này. Xin vui lòng nạp thêm tiền vào tài
	 *        	khoản.");
	 *        	$this->redirect(array('/member/about'));
	 *        	}
	 *        	}
	 *        	}
	 *        	else{
	 *        	$criteriaE=new CDbCriteria();
	 *        	$criteriaE->condition = 't.fid = '.$model->id.' AND
	 *        	t.active=1';
	 *        	$criteriaE->order='t.order DESC';
	 *        	$dataProviderE=new CActiveDataProvider('Server', array(
	 *        	'criteria'=>$criteriaE,
	 *        	'pagination'=>array(
	 *        	'pageSize'=>5,
	 *        	),
	 *        	));
	 *        	$criteriaF=new CDbCriteria();
	 *        	$criteriaF->condition = 't.id != '.$model->id.' AND
	 *        	catid='.$model->catid.' AND t.active=1';
	 *        	$criteriaF->order='t.order DESC';
	 *        	$dataProviderF=new CActiveDataProvider('Film', array(
	 *        	'criteria'=>$criteriaF,
	 *        	'pagination'=>array(
	 *        	'pageSize'=>5,
	 *        	),
	 *        	));
	 *        	$this->render('view',array(
	 *        	'model'=>$model,
	 *        	'dataProviderE'=>$dataProviderE,
	 *        	'dataProviderF'=>$dataProviderF,
	 *        	));
	 *        	}
	 *        	}
	 *        	else{
	 *        	if($show!=''){
	 *        	$Session= new Session('Script');
	 *        	$Session->set('fs',time());
	 *        	$Session->set('id',$id);
	 *        	$appid=Yii::app()->params['applicationId'];
	 *        	$appsecret=Yii::app()->params['appSecret'];
	 *        	$p='film_'.$id;
	 *        	$s=$Session->Get('fs');
	 *        	$md5=md5($appid.$p.$appsecret.$s);
	 *        	$link=Yii::app()->params['paymentUrl'].'?a='.$appid.'&p='.$p.'&s='.$s.'&md5='.$md5;
	 *        	$this->redirect($link);
	 *        	}
	 *        	else{
	 *        	$this->redirect(array('/site/login'));
	 *        	}
	 *        	}
	 *        	}
	 */
	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view'
	 * page.
	 *
	 * public function actionCreate()
	 * {
	 * $model=new Film;
	 *
	 * // Uncomment the following line if AJAX validation is needed
	 * // $this->performAjaxValidation($model);
	 *
	 * if(isset($_POST['Film']))
	 * {
	 * $model->attributes=$_POST['Film'];
	 * if($model->save())
	 * $this->redirect(array('view','id'=>$model->id));
	 * }
	 *
	 * $this->render('create',array(
	 * 'model'=>$model,
	 * ));
	 * }
	 */
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view'
	 * page.
	 * 
	 * @param integer $id
	 *        	the ID of the model to be updated
	 *        	
	 *        	public function actionUpdate($id)
	 *        	{
	 *        	$model=$this->loadModel($id);
	 *        	
	 *        	// Uncomment the following line if AJAX validation is needed
	 *        	// $this->performAjaxValidation($model);
	 *        	
	 *        	if(isset($_POST['Film']))
	 *        	{
	 *        	$model->attributes=$_POST['Film'];
	 *        	if($model->save())
	 *        	$this->redirect(array('view','id'=>$model->id));
	 *        	}
	 *        	
	 *        	$this->render('update',array(
	 *        	'model'=>$model,
	 *        	));
	 *        	}
	 */
	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin'
	 * page.
	 * 
	 * @param integer $id
	 *        	the ID of the model to be deleted
	 *        	
	 *        	public function actionDelete($id)
	 *        	{
	 *        	if(Yii::app()->request->isPostRequest)
	 *        	{
	 *        	// we only allow deletion via POST request
	 *        	$this->loadModel($id)->delete();
	 *        	
	 *        	// if AJAX request (triggered by deletion via admin grid
	 *        	view), we should not redirect the browser
	 *        	if(!isset($_GET['ajax']))
	 *        	$this->redirect(isset($_POST['returnUrl']) ?
	 *        	$_POST['returnUrl'] : array('admin'));
	 *        	}
	 *        	else
	 *        	throw new CHttpException(400,'Invalid request. Please do not
	 *        	repeat this request again.');
	 *        	}
	 */
	/**
	 * Lists all models.
	 */
	public function actionIndex() {
        //New
        $criteriaNew = new CDbCriteria();
        $criteriaNew->limit = 5;
        $criteriaNew->order = 't.order DESC';
        $dataProviderNew = new CActiveDataProvider('Film', array(
            'criteria' => $criteriaNew,
            'pagination' => false,
        ));


        //get list Film category for render Film dataprovider
        $criteriaCatFilm = new CDbCriteria();
        $criteriaCatFilm->select = array('id', 'name');
        $criteriaCatFilm->order = 't.order ASC';
        $FilmCategory = Category::model()->findAll($criteriaCatFilm);

        $dataProviderFilmArr = array();
        foreach ($FilmCategory as $FilmCategoryData) {
            $dataProviderFilm = new CActiveDataProvider('Film', array(
                'criteria' => array(
                    'order' => 't.id DESC',
                    'condition' => 'catid = ' . $FilmCategoryData->id,
                    'limit' => 5,
                ),
                'pagination' => false,
            ));
            //push dataprovider to Filmarr
            array_push($dataProviderFilmArr, $dataProviderFilm);
        }

        $this->render('index', array(
            'dataProviderNew' => $dataProviderNew,
            'dataProviderFilmArr' => $dataProviderFilmArr,
            'FilmCategory' => $FilmCategory,
        ));
	}
	
	/**
	 * Lists all models.
	 */
	public function actionNew() {
		// New
		$criteriaNew = new CDbCriteria ();
		$criteriaNew->condition = "t.active=1";
		$criteriaNew->order = 't.id DESC';
		$dataProviderNew = new CActiveDataProvider ( 'Film', array (
				'criteria' => $criteriaNew,
				'pagination' => array (
						'pageSize' => 10 
				) 
		) );
		$this->render ( 'new', array (
				'dataProviderNew' => $dataProviderNew 
		) );
	}
	
	/**
	 * Lists all models hot.
	 */
	public function actionHot() {
		// Hot
		$criteriaHot = new CDbCriteria ();
		$criteriaHot->condition = "t.hot=1 AND t.active=1";
		// $criteriaHot->limit = 5;
		$criteriaHot->order = 't.order DESC';
		$dataProviderHot = new CActiveDataProvider ( 'Film', array (
				'criteria' => $criteriaHot,
				'pagination' => array (
						'pageSize' => 10 
				) 
		) );
		$this->render ( 'hot', array (
				'dataProviderHot' => $dataProviderHot 
		) );
	}
	
	/**
	 * Manages all models.
	 *
	 * public function actionAdmin()
	 * {
	 * $model=new Film('search');
	 * $model->unsetAttributes(); // clear any default values
	 * if(isset($_GET['Film']))
	 * $model->attributes=$_GET['Film'];
	 *
	 * $this->render('admin',array(
	 * 'model'=>$model,
	 * ));
	 * }
	 */
	/**
	 * Returns the data model based on the primary key given in the GET
	 * variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * 
	 * @param
	 *        	integer the ID of the model to be loaded
	 */
	public function loadModel($id) {
		$model = Film::model ()->findByPk ( $id );
		if ($model === null)
			throw new CHttpException ( 404, 'The requested page does not exist.' );
		return $model;
	}
	
	/**
	 * Performs the AJAX validation.
	 * 
	 * @param
	 *        	CModel the model to be validated
	 */
	protected function performAjaxValidation($model) {
		if (isset ( $_POST ['ajax'] ) && $_POST ['ajax'] === 'film-form') {
			echo CActiveForm::validate ( $model );
			Yii::app ()->end ();
		}
	}
}
